package cn.wmingming.e3mall.order.interceptor;

import cn.wmingming.common.jedis.JedisClient;
import cn.wmingming.common.pojo.E3Result;
import cn.wmingming.common.utils.CookieUtils;
import cn.wmingming.common.utils.JsonUtils;
import cn.wmingming.e3mall.pojo.TbUser;
import cn.wmingming.e3mall.sso.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Value("${COOKIES_TOKEN}")
    private String COOKIES_TOKEN;
    @Value("${LOGIN_URL}")
    private String LOGIN_URL;
    @Value("${LOCAL_URL}")
    private String LOCAL_URL;
    @Autowired
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //目标方法执行前
        //返回true，放行	false：拦截

        //1 从cookies缓存中获取token
        String cookieValue = CookieUtils.getCookieValue(httpServletRequest, COOKIES_TOKEN);
        if(StringUtils.isBlank(cookieValue)){
            //2 token为空，跳到登录页面,拦截
            httpServletResponse.sendRedirect(LOGIN_URL+"?redirect="+LOCAL_URL);
            return false;
        }
        //3 token不为空,去服务器获得用户数据
        E3Result result = userService.getUserByToken(cookieValue);
        if(result.getStatus() != 200){
            //4 redis数据是过期，跳到登录页面,拦截
            httpServletResponse.sendRedirect(LOGIN_URL+"?redirect="+LOCAL_URL);
            return false;
        }
        //5 redis数据有效,将用户数据放进request域,放行
        TbUser user = (TbUser) result.getData();
        httpServletRequest.setAttribute("user",user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        //目标方法执行后，返回modelAndView前
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        //返回modelAndView后
    }
}
